package org.opens.mybatisplus.controller;

import cn.hutool.core.collection.CollectionUtil;
import org.opens.mybatisplus.entity.TreeNodeEntity;
import org.opens.mybatisplus.service.TreeNodeEntityService;
import org.opens.util.R;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * (TreeNodeEntity)表控制层
 *
 * @author makejava
 * @since 2020-05-28 16:53:59
 * 注意:
 *      1. 必须使这个类
 */
@RestController(value = "treeNodeEntityController")
@RequestMapping("/api")
public class TreeNodeEntityController {
    /**
     * 服务对象
     */
    @Resource
    private TreeNodeEntityService treeNodeEntityService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/treeNode/{id}")
    public TreeNodeEntity selectOne(
            @PathVariable(value = "id") Integer id
    ) {
        return this.treeNodeEntityService.queryById(id);
    }

    @GetMapping(value = "/treeNode/{topNodeId}/children")
    public R queryOfBottomNodeByTopNodeId(
            @PathVariable(value = "topNodeId") Integer topNodeId,
            @RequestParam(value = "id", required = false) Integer id
    ) {
        R ok = R.success("ok");
        List<TreeNodeEntity> treeNodes = treeNodeEntityService.queryOfBottomNodeByTopNodeId(topNodeId);
        Map<Integer, TreeNodeEntity> treeNodesCacheMap = new HashMap<>();
        if(CollectionUtil.isNotEmpty(treeNodes)) {
            treeNodesCacheMap = treeNodes.stream().collect(Collectors.toMap(TreeNodeEntity::getId, x -> x, (oldValue, newValue) -> newValue));
        }
        //用Optional实现去除冗余if...else...判断, 不熟悉Optional的话可能看起来不容器懂, 但是懂了之后会发现Optional帮助我们做了好多控制判断, 可以让代码报错空指针异常的概率大大降低
        String name = Optional.ofNullable(treeNodesCacheMap.get(id)).map(x -> String.format("缓存中取出了%d对应的数据的name属性: %s", id, x.getName())).orElseGet(() -> {
            return Optional.ofNullable(treeNodeEntityService.queryById(id)).map(x -> String.format("数据库中取出了%d对应的数据的name属性: %s", id, x.getName())).orElse("数据库中没有这个id对应的值");
        });
        ok.put("result", treeNodes);
        ok.put("treeNodesCacheMap", treeNodesCacheMap);
        ok.put("name", name);
        return ok;
    }

}